package com.adgox.tiantianbiting.mine.wallet;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.adgox.tiantianbiting.R;
import com.adgox.tiantianbiting.TtbtApplication;
import com.adgox.tiantianbiting.bean.BaseResponseBean;
import com.adgox.tiantianbiting.bean.RechargeBean;
import com.adgox.tiantianbiting.bean.RechargeInfoBean;
import com.adgox.tiantianbiting.bean.UserInfo;
import com.adgox.tiantianbiting.mine.login.LoginActivity;
import com.adgox.tiantianbiting.mine.tingCoinRecord.TingCoinRecordActivity;
import com.adgox.tiantianbiting.mine.tradeRecord.TradeRecordActivity;
import com.adgox.tiantianbiting.net.callback.JsonCallback;
import com.adgox.tiantianbiting.utils.ApiConstant;
import com.adgox.tiantianbiting.widget.MyGridView;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.rae.swift.session.SessionManager;
import com.tencent.mm.opensdk.modelbiz.WXLaunchMiniProgram;
import com.tencent.mm.opensdk.modelpay.PayReq;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MyWalletActivity extends AppCompatActivity implements MyWalletContract.View, AdapterView.OnItemClickListener, View.OnClickListener {

    @BindView(R.id.tv_balance)
    TextView tvBalance;
    @BindView(R.id.tv_bonus)
    TextView tvBonus;
    @BindView(R.id.grid_view)
    MyGridView gridView;
    private MyWalletContract.Presenter mPresenter;
    private String cny;
    private List<RechargeInfoBean> mList;
    private Dialog dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_wallet);
        ButterKnife.bind(this);

        new MyWalletPresenterImpl(this);
        mPresenter.getRechargeInfo();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //获取用户金额
        UserInfo user = SessionManager.getDefault().getUser();
        OkGo.<BaseResponseBean<UserInfo>>get(ApiConstant.BASE_URL + ApiConstant.GET_BALANCE + user.getId())
                .execute(new JsonCallback<BaseResponseBean<UserInfo>>() {
                    @Override
                    public void onSuccess(Response<BaseResponseBean<UserInfo>> response) {
                        if (!"0".equals(response.body().getCode())) {
                            Toast.makeText(MyWalletActivity.this, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                            return;
                        }
                        if (response.body().getData() == null) {
                            return;
                        }
                        tvBalance.setText("" + response.body().getData().getBalance());
                        tvBonus.setText("" + response.body().getData().getCommission());
                        SessionManager.getDefault().setUser(response.body().getData());
                    }
                });
    }

    @Override
    public void setPresenter(MyWalletContract.Presenter presenter) {
        mPresenter = presenter;
    }

    @OnClick(R.id.img_finish)
    public void onFinishClicked() {
        finish();
    }

    @Override
    public void onSetRechargeInfo(List<RechargeInfoBean> list) {
        mList = list;
        ArrayList<Map<String, Object>> rechargeInfoList = new ArrayList<>();
        for (int i = 1; i < list.size(); i++) {
            HashMap<String, Object> map = new HashMap<>();
            map.put("ting", (list.get(i).getTingCoin() + list.get(i).getDiscountValue())+ "听币");
            map.put("cny", list.get(i).getCnyCoin() + "元");
            map.put("more", "多送" + list.get(i).getDiscountValue() + "元");
            map.put("fire", list.get(i).isSellWell() ? R.drawable.icon_fire : null);
            rechargeInfoList.add(map);
        }
        String[] from = {"ting", "cny", "more", "fire"};
        int[] to = {R.id.tv_ting_coin, R.id.tv_cny_coin, R.id.tv_more, R.id.iv_fire};
        SimpleAdapter adapter = new SimpleAdapter(this, rechargeInfoList, R.layout.item_grid_view_recharge, from, to);
        gridView.setAdapter(adapter);
        gridView.setOnItemClickListener(this);

    }

    @OnClick(R.id.fl_record)
    public void onRecordClicked() {
        Intent intent = new Intent(MyWalletActivity.this, TradeRecordActivity.class);
        startActivity(intent);
    }

    @OnClick(R.id.tv_pay)
    public void onRechargeClicked() {
        if (!TtbtApplication.wxapi.isWXAppInstalled()) {
            Toast.makeText(this, "请先安装微信客户端", Toast.LENGTH_SHORT).show();
            return;
        }
        if (cny == null) {
            Toast.makeText(this, "请选择要充值的面额", Toast.LENGTH_SHORT).show();
            return;
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("body", "天天必听充值");
        map.put("price", cny);
        map.put("userId", ((UserInfo) SessionManager.getDefault().getUser()).getId());
        Gson gson = new Gson();
        String s = gson.toJson(map);
        OkGo.<BaseResponseBean<RechargeBean>>post(ApiConstant.BASE_URL + ApiConstant.WX_PAY)
                .upJson(s)
                .execute(new JsonCallback<BaseResponseBean<RechargeBean>>() {
                    @Override
                    public void onSuccess(Response<BaseResponseBean<RechargeBean>> response) {
                        if (!"0".equals(response.body().getCode())) {
                            Toast.makeText(MyWalletActivity.this, "获取支付信息失败", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        wxPay(response.body().getData());
                    }
                });
    }

    private void wxPay(RechargeBean data) {
        PayReq req = new PayReq();
        req.appId = data.getAppId();
        req.partnerId = data.getPartnerId();
        req.prepayId = data.getPrepayId();
        req.nonceStr = data.getNonceStr();
        req.timeStamp = data.getTimeStamp();
        req.packageValue = data.getPackageValue();
        req.sign = data.getSign();
        TtbtApplication.wxapi.sendReq(req);
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        for (int m = 0; m < adapterView.getCount(); m++) {
            ViewGroup v = (ViewGroup) adapterView.getChildAt(m);
            if (m == i) {
                ((ViewGroup) view).getChildAt(0).setBackgroundResource(R.drawable.bg_textview_buy_dialog_selected);
            } else {
                v.getChildAt(0).setBackgroundResource(R.drawable.bg_textview_buy_dialog_unselected);
            }
        }
        if (mList == null) return;
        cny = mList.get(i+1).getCnyCoin() + "";
    }

    public void toWXLittleProgram() {
        dialog = new Dialog(this, R.style.TransparentDialog);
        Window window = dialog.getWindow();
        window.requestFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.dialog_towx);
        ImageView iconTowx = dialog.findViewById(R.id.icon_towx);
        ImageView iconCancel = dialog.findViewById(R.id.icon_cancel);
        iconTowx.setOnClickListener(this);
        iconCancel.setOnClickListener(this);
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
    }

    @OnClick({R.id.tv_bonus, R.id.fl_record_coin})
    public void onViewClicked(View view) {
//        toWXLittleProgram();
        startActivity(new Intent(this, TingCoinRecordActivity.class));
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.icon_towx:
                //跳小程序
                if (!TtbtApplication.wxapi.isWXAppInstalled()) {
                    Toast.makeText(this, "请先安装微信客户端", Toast.LENGTH_SHORT).show();
                    return;
                }
                WXLaunchMiniProgram.Req req = new WXLaunchMiniProgram.Req();
                req.userName = "gh_b77d7ffeec87";
                req.path = "/pages/my/mydetail/mydetail?showhomeicon=fx";
                req.miniprogramType = WXLaunchMiniProgram.Req.MINIPTOGRAM_TYPE_RELEASE;
                TtbtApplication.wxapi.sendReq(req);
            case R.id.icon_cancel:
                dialog.dismiss();
                break;
        }
    }
}
